<template>
  <div class="proMeg">
    <div class="proMeg_tit">
      <span class="hover before"
            @click="addTitle='',setting=false,getList()">{{title}}</span>
      <span v-show="setting"><span class="xie">{{'  /  '}}</span><i class="hover">{{addTitle}}</i> </span>

      <!-- <gl-breadcrumb class="mb15"
                     :text="setting?'AI交互技能组管理,技能设置':'AI交互技能组管理'"></gl-breadcrumb> -->
    </div>
    <div class="proMeg_main">
      <div v-if="!setting"
           class="proMeg_main_nav">
        <el-select class="mr20"
                   v-model="portId"
                   placeholder="请选择端口"
                   clearable
                   @change="getList">
          <el-option v-for="item in portList"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
        <el-select class="mr20"
                   v-model="types"
                   clearable
                   @change="getList"
                   placeholder="请选择类型">
          <el-option v-for="item in typeList"
                     :key="item.sg_id"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
        <el-input class="mr20"
                  v-model="proName"
                  style="width:200px"
                  placeholder="请输入名称查询"></el-input>
        <div>
          <el-button type="primary"
                     icon="el-icon-search"
                     @click="getList">
            搜索
          </el-button>
          <el-button type="primary"
                     icon="el-icon-plus"
                     @click="add">
            新建
          </el-button>
        </div>
      </div>
      <div v-else
           class="proMeg-main-nav">
        <p class="nav-title">
          {{navTitle}}
        </p>
        <el-button type="primary"
                   @click="addLink()">
          添加关联
        </el-button>
      </div>
      <div class="proMeg_main_box">
        <gl-table @button="buttonClick"
                  :data="setting?data[1]:data[0]"
                  :defaultTab="setting?false:true"
                  :columns="setting?columns[1]:columns[0]"></gl-table>
        <gl-pagination v-if="!setting"
                       :curr="curr"
                       :size="pageSize"
                       :total="total"
                       @callback="currChange"></gl-pagination>
      </div>
    </div>
    <Gldelbtn :show="showDel"
              :text="dialogText"
              @cancel="closeDel"
              @determine="determine"></Gldelbtn>

    <el-dialog :title="dialogTitle"
               :visible.sync="dialogVis"
               :before-close="handleClose">
      <gl-form v-if="!setting"
               :form="form"
               ref="glForm"
               :formLabel="formLabel"
               @upload="upload"
               @removeImg="removeImg"
               :must="must">
      </gl-form>

      <gl-form v-if="setting&&!showTree"
               :form="nodeData"
               ref="glForm2"
               :formLabel="nodeForm"
               :must="nodeDataMust">
        <template>
          <div slot="setting"
               class="parameter-box">
            <div v-for="(item,index) in nodeData.list"
                 :key="index">
              <div class="parameter-list">
                <input type="text"
                       class="label mr10"
                       v-model="item.key_name"
                       placeholder="参数名">
                <span>:</span>
                <input type="text"
                       class="value ml10"
                       v-model="item.value"
                       placeholder="参数值">
                <span class="del"
                      @click="delParameter(nodeData.list,index)"> x </span>
              </div>
            </div>
            <el-button type="primary"
                       @click="addParameter(nodeData)">
              + 添加设备参数项
            </el-button>
          </div>
        </template>
      </gl-form>

      <div v-if="setting&&showTree"
           class="block">
        <div class="search-tree">

          <el-input placeholder="请输入搜索内容"
                    v-model="keyword">
            <i slot="suffix"
               class="el-input__icon el-icon-search"
               @click="getNodeList(portType)"></i>
          </el-input>
          <el-button type="primary"
                     @click="addSkill('')">
            + 新增
          </el-button>
        </div>
        <div class="treeBox">
          <el-tree :data="dataList"
                   show-checkbox
                   node-key="id"
                   ref="tree"
                   default-expand-all
                   :expand-on-click-node="false">
            <div class="custom-tree-node por"
                 slot-scope="{ node, data }">
              <el-col :span="12">
                <el-dropdown trigger="click"
                             @command="ItemNode">
                  <span class="el-dropdown-link"
                        @click="() => getNode(node)">
                    <span>{{ data.name }}</span>
                    <span>
                      <el-button type="text"
                                 size="mini">
                        <i class="el-icon-edit ml15"
                           style="color:#000;"></i>
                      </el-button>
                    </span>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add">新增子功能</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </div>
          </el-tree>
        </div>

        <el-dialog :title="innerTitle"
                   :visible.sync="innerVisible"
                   append-to-body>
          <gl-form :form="nodeData"
                   ref="nodeDate"
                   @upload="(res, prop) => nodeData[prop] = res[0].savepath"
                   :formLabel="nodeForm"
                   :must="nodeDataMust">
            <template>
              <div slot="setting"
                   class="parameter-box">
                <div v-for="(item,index) in nodeData.list"
                     :key="index">
                  <div class="parameter-list">
                    <input type="text"
                           class="label mr10"
                           v-model="item.key_name"
                           placeholder="参数名">
                    <span>:</span>
                    <input type="text"
                           class="value ml10"
                           v-model="item.value"
                           placeholder="参数值">
                    <span class="del"
                          @click="delParameter(nodeData.list,index)"> x </span>
                  </div>
                </div>
                <el-button type="primary"
                           @click="addParameter(nodeData)">
                  + 添加设备参数项
                </el-button>
              </div>
            </template>
          </gl-form>
          <span slot="footer"
                class="dialog-footer">
            <el-button @click="innerVisible = false">取 消</el-button>
            <el-button type="primary"
                       @click="submitSonNode(false)">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVis = false">取 消</el-button>
        <el-button type="primary"
                   @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'AIskillMeg',
  data() {
    return {
      loading: false,
      showTree: false, //控制
      uploadRes: { _icon: '', icon: '' },
      portType: '',
      keyword: '',
      type: '',
      skill_id: '',
      title: 'AI交互技能组管理',
      addTitle: '',
      innerTitle: '',
      navTitle: '',
      portList: [
        { label: '家长端', value: '1' },
        { label: '设备端', value: '2' }
      ], //客户下拉列表
      portId: '',
      typeList: [], //状态列表
      types: '',
      proName: '',
      data: [[], []],
      columns: [
        [
          { label: 'ID', prop: 'skill_id' },
          { label: '名称', prop: 'skill_name' },
          { label: '应用端口', prop: 'type_msg' },
          { label: '技能类型', prop: 'sg_name' },
          { label: '调用产品数', prop: 'products' },
          { label: '更新时间', prop: 'update_time' },
          {
            label: '操作',
            btns: ['技能点详情', '编辑', '删除'],
            class: 'btn',
            width: '200'
          }
        ],
        [
          { label: '技能ID', prop: 'id' },
          { label: '技能点名称', prop: 'name' },
          { label: '触发关键词', prop: 'keywords' },
          { label: '执行结果', prop: 'answer' },
          { label: '回复语句', prop: 'reply_text' },
          { label: '更新时间', prop: 'update_time' },
          {
            label: '操作',
            btns: ['编辑', '删除'],
            class: 'btn'
          }
        ]
      ],
      curr: 1,
      pageSize: 10,
      total: 0,
      dialogVis: false,
      innerVisible: false,
      dialogTitle: '',
      form: {
        skill_name: '',
        type: '',
        g_id: '',
        icon: '',
        _icon: '',
        description: ''
      },
      formLabel: [
        { label: '技能组名称：', prop: 'skill_name', placeholder: '请输入' },
        {
          label: '端口类型：',
          prop: 'type',
          options: [
            { label: '家长端', value: 1 },
            { label: '设备端', value: 2 }
          ]
        },
        { label: '技能类型：', prop: 'g_id', options: [] },
        {
          label: 'icon：',
          prop: 'icon',
          type: 'upload',
          limit: 1
        },
        {
          label: '描述：',
          prop: 'description',
          type: 'textarea',
          text: 'ueditor',
          placeholder: '请输入'
        }
      ],
      nodeData: {},
      nodeForm: [
        { label: '技能名称', prop: 'name' },
        { label: '触发关键词', prop: 'keywords' },
        { label: '事件答案', prop: 'answer' },
        { label: '回复语句', prop: 'reply_text' },
        { label: '包名', prop: 'app_name' },
        { label: '类名', prop: 'class_name' },
        { label: '设置参数', slot: 'setting', prop: 'list' }
      ],
      nodeDataMust: 'name',
      must: 'skill_name,type,g_id,icon',
      showDel: false,
      dialogText: '',
      setting: false,
      dataInfo: {
        id: '',
        name: '',
        keywords: '',
        answer: '',
        reply_text: '',
        app_name: '',
        class_name: '',
        list: []
      },
      nodeId: '',
      //无限分类列表
      dataList: [],
      savePath: '',
      uis: '',
      uisArr: [],
      delskillId: '',
      settingList: {},
      showList: [],
      type: '',
      o: 0
    }
  },
  created() {
    this.getList()
    this.getTypeList()
  },
  watch: {},
  updated() {
    // this.$refs.tree && this.$refs.tree.setCheckedNodes(this.uisArr)
    this.$refs.tree &&
      Object.keys(this.settingList.list).map(e => {
        this.$refs.tree.setChecked(e, true)
      })
  },
  methods: {
    removeImg(val) {
      //   console.log(val)
    },
    addLink() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$nextTick(() => {
        setTimeout(() => {
          this.dialogVis = true
          this.showTree = true
          //   console.log();

          this.dialogTitle = '关联技能点'
          loading.close()
        }, 200)
      })
    },
    upload(res) {
      //   console.log(res)
      // return;
      this.savePath = res.savepath
    },
    ItemNode(fea) {
      if (fea == 'add') {
        // console.log('新建')
        this.addSkill(this.nodeId)
      } else if (fea == 'edit') {
        this.innerTitle = '修改AI功能'
        this.innerVisible = true
        this.$refs.nodeDate && this.$refs.nodeDate.clearValidate()

        this.getSonNode(this.nodeId)
      } else {
        // console.log('del')
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.delNode(this.nodeId)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    },
    getNode(node) {
      //   console.log(node)
      this.nodeId = node.key
      //   console.log(this.nodeId)
      // this.nodeData = node.data
    },

    delNode(id) {
      this.http
        .$post('admin/svoice.Api/del_ui_fn', { id, del: '2' })
        .then(r => {
          //   console.log(r)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getNodeList(this.portType)
        })
        .catch(this.$err)
    },
    getSkillInfo(skill_id) {
      this.http
        .$post('admin/skill.api/get_skill_info', { skill_id })
        .then(r => {
          //   console.log(r)
          this.form = r
          this.form.icon = r._icon
          this.uploadRes.icon = r.icon
          this.uploadRes._icon = r._icon

          this.dialogVis = true
        })
        .catch(this.$err)
    },
    getTypeList() {
      this.http
        .$post('admin/skill.Api/group_skill')
        .then(r => {
          //   console.log(r)
          r = r.map(item => ({
            label: item.sg_name,
            value: item.sg_id,
            ...item
          }))
          this.typeList = r
          this.formLabel[2].options = r
        })
        .catch(this.$err)
    },
    callback(list, temp, flag) {
      //   console.log(temp)
      // let o = 0
      if (this.o <= temp.length) {
        for (let i in list) {
          let e = list[i]
          if (temp.includes(e.id.toString())) {
            this.o++
            // console.log(this.o)
            //   console.log(flag)
            flag == true && !this.showList.includes(e) && this.showList.push(e)
            // console.log(this.showList)
            Object.assign(e, this.settingList.list[e.id])
            if (e.children && e.children.length) {
              Object.assign(e, this.settingList.list[e.id])
              this.callback(e.children, temp, false)
            }
          } else if (e.children && e.children.length) {
            this.callback(e.children, temp, true)
          }
          // console.log(this.showList);
          //   o++
          continue
        }
      }
      //   console.log(this.showList)

      //   console.log(o)
    },
    getNodeList(type) {
      this.portType = type
      this.http
        .$post(
          'admin/svoice.Api/list_f_children',
          {
            type,
            keyword: this.keyword
          },
          { loading: true }
        )
        .then(r => {
          //   console.log(r)
          //   let temp = Object.keys(this.settingList.list)
          //   console.log([...temp])

          if (r.children && r.children.length) {
            this.dataList = r.children
            let temp = Object.keys(this.settingList.list)
            // console.log([...temp])
            this.showList = []
            this.callback(r.children, temp, true)
            this.data[1].splice(0, this.data[1].length, ...this.showList)
          } else {
            this.dataList = []
            this.data[1].splice(0, this.data[1].length)
          }
        })
        .catch(this.$err)
    },

    getSonNode(id) {
      this.http
        .$post('admin/svoice.Api/get_ui_fn', { id })
        .then(r => {
          //   console.log(r)
          this.nodeData = r
        })
        .catch(this.$err)
    },
    skill_Operation() {
      this.http
        .$post('admin/skill.api/save_skill', {
          skill_id: this.skill_id,
          skill_name: this.navTitle,
          uis: this.uis
        })
        .then(r => {
          //   console.log(r)
          this.getSetList(this.skill_id)
          setTimeout(() => {
            this.dialogVis = false
            this.showDel = false
            this.$message.success('操作成功')
          }, 200)
        })
        .catch(this.$err)
    },
    submitSonNode(flag) {
      if (flag) {
        let temp = []
        this.$refs.tree.getCheckedNodes().map(e => {
          if (!temp.includes(e.id)) {
            temp.push(e.id)
          }
        })
        this.uis = temp.join('|')
        // console.log(this.uis)
        // return;
        this.skill_Operation()
      } else {
        if (
          this.showTree
            ? this.$refs.nodeDate.validate()
            : this.$refs.glForm2.validate()
        ) {
          this.http
            .$post('admin/svoice.Api/save_ui_fn', this.nodeData)
            .then(r => {
              //   console.log(r)
              this.getSetList(this.skill_id)
              setTimeout(() => {
                this.nodeData = {}
                this.innerVisible = false
                if (!this.showTree) {
                  this.dialogVis = false
                }
                this.$message.success('编辑成功')
              }, 200)
              //   this.getNodeList(this.portType)
            })
            .catch(this.$err)
        } else {
          return this.$message.error('请确认输入是否完整无误')
        }
      }
    },
    addParameter(node) {
      node.list.push({ key_name: '', value: '' })
      //   console.log(node.list)
    },
    delParameter(item, index) {
      // console.log(item,index);
      item.splice(index, 1)
      // console.log(this.nodeData);
    },
    addSkill(pid) {
      this.innerVisible = true

      this.innerTitle = '新增技能点'
      this.curr = 1
      this.pageSize = 10
      this.total = 0
      this.nodeData = {
        pid,
        name: '',
        keywords: '',
        answer: '',
        reply_text: '',
        app_name: '',
        class_name: '',
        list: []
      }
      this.$refs.nodeData && this.$refs.nodeDate.clearValidate()
      // console.log(this.$refs.nodeDate);
    },
    getList(obj) {
      if (obj) {
        this.curr = obj.curr
        this.pageSize = obj.size
      } else {
        this.curr = 1
        this.pageSize = 10
      }
      this.http
        .$post(
          'admin/skill.api/list_skill',
          {
            curr: this.curr,
            limits: this.pageSize,
            type: this.portId,
            g_id: this.types,
            keyword: this.proName
          },
          { loading: true }
        )
        .then(r => {
          //   console.log(r)
          this.total = r.total
          if (r.total) {
            this.data[0].splice(0, this.data[0].length, ...r.list)
          } else {
            this.data[0].splice(0, this.data[0].length)
          }
        })
        .catch(this.$err)
    },
    getSetList(skill_id, obj) {
      if (obj) {
        this.curr = obj.curr
        this.pageSize = obj.size
      } else {
        this.curr = 1
        this.pageSize = 10
      }
      this.skill_id = skill_id
      this.http
        .$post('admin2/skill.api/skill_fn_list', {
          skill_id,
          curr: this.curr,
          limits: this.limits
        })
        .then(r => {
          //   console.log(r)
          this.settingList = r

          this.getNodeList(this.type == '1' ? '2' : this.type == '2' ? '1' : '')

          //   this.total = r.total
          //   if (r.total) {
          //     this.data[1].splice(0, this.data[1].length, ...r.list)
          //   } else {
          //     this.data[1].splice(0, this.data[1].length)
          //   }
        })
        .catch(this.$err)
    },
    closeDel() {
      this.showDel = false
    },
    buttonClick(obj) {
      // console.log(obj)
      if (this.setting) {
        if (obj.index * 1 === 1) {
          //   console.log(obj)
          this.delskillId = obj.row.id.toString()
          this.dialogText = obj.row.name
          this.showDel = true
        } else {
          this.dialogTitle = '编辑技能点'
          this.dialogVis = true
          this.showTree = false
          this.getSonNode(obj.row.id)
        }
      } else {
        //   console.log(obj);
        //   return;
        this.skill_id = obj.row.skill_id
        if (obj.index * 1 === 1) {
          //   console.log('编辑')
          this.dialogTitle = '编辑技能组'
          this.$refs.glForm && this.$refs.glForm.clearValidate()
          this.getSkillInfo(obj.row.skill_id)
        } else if (obj.index * 1 === 2) {
          this.dialogText = obj.row.skill_name
          this.showDel = true
        } else {
          //   console.log(obj)
          this.navTitle = obj.row.skill_name
          this.setting = true
          this.uis = obj.row.uis
          this.uis && (this.uisArr = obj.row.uis.split('|'))
          //   console.log(this.uis)
          this.addTitle = '技能设置'
          this.getSetList(obj.row.skill_id)
          this.type = obj.row.type
          //   this.getNodeList(
          //     obj.row.type == '1' ? '2' : obj.row.type == '2' ? '1' : ''
          //   )
        }
      }
    },
    delSkill() {
      this.http
        .$post('admin/skill.api/set_status', {
          skill_id: this.skill_id,
          status: 3
        })
        .then(r => {
          //   console.log(r)
          this.showDel = false
          this.$message.success('删除成功')
          this.getList()
        })
        .catch(this.$err)
    },
    determine(code, Vcode) {
      //   console.log(code, Vcode)
      if (code === Vcode) {
        this.dialogVis = false
        if (this.setting) {
          if (this.uisArr.includes(this.delskillId)) {
            this.uisArr.splice(this.uisArr.indexOf(this.delskillId), 1)
          }
          this.uis = this.uisArr.join('|')
          this.skill_Operation()
        } else {
          this.delSkill()
        }
      } else {
        this.$message.error('验证码错误，请确认后重新输入')
      }
    },
    submit() {
      // console.log(this.form);
      // return;
      if (!this.setting) {
        if (this.$refs.glForm.validate()) {
          let params = {
            g_id: this.form.g_id,
            description: this.form.description,
            skill_name: this.form.skill_name,
            icon: this.savePath,
            price: this.form.price,
            device_class: this.form.device_class,
            uis: this.form.uis,
            skill_id: this.form.skill_id || '',
            type: this.form.type
          }
          // console.log(params)
          // return
          this.http
            .$post('admin/skill.api/save_skill', params)
            .then(r => {
              //   console.log(r)
              this.dialogVis = false

              this.getList()
            })
            .catch(this.$err)
        } else {
          return this.$message.error('请确认输入是否完整无误')
        }
      } else {
        // console.log('111')
        this.showTree ? this.submitSonNode(true) : this.submitSonNode()
      }
    },
    currChange(obj) {
      //   console.log(obj)

      //   if (!this.setting) {
      this.getList(obj)
      //   } else {
      //     this.getSetList(this.skill_id, obj)
      //   }
    },
    add() {
      this.form = {}
      this.uploadRes = {}
      this.dialogTitle = '新增技能组'
      this.dialogVis = true
      //   this.$refs.glForm && this.$refs.glForm.clearValidate()
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.el-dialog__header {
  border-bottom: 1px solid #ddd;
}
/deep/.el-input__suffix {
  cursor: pointer;
}
.proMeg {
  // background-color: #fff;
  .proMeg_tit {
    padding: 15px 0 15px 25px;
    background-color: #fff;
    margin-bottom: 20px;
    font-size: 14px;
    .hover {
      cursor: pointer;
      color: #606266;
    }
    .xie {
      font-weight: bold;
      color: #ccc;
      margin: 0 9px;
    }
    .before {
      color: #000;
      font-weight: bold;
      &:hover {
        color: #409eff;
      }
    }
  }
  .proMeg_main {
    padding: 20px 25px;
    background-color: #fff;
    .proMeg_main_nav {
      display: flex;
    }
    .proMeg-main-nav {
      display: flex;
      justify-content: space-between;
    }
    .nav-title {
      font-size: 20px;
    }
    .proMeg_main_box {
      margin-top: 20px;
      /deep/ .el-table .cell {
        .el-button--text {
          &.btn {
            margin: 0;
            span {
              padding: 0 5px;
              border-right: 1px solid #66b1ff;
            }
            &:last-child {
              span {
                border: none;
              }
            }
          }
        }
      }
    }
  }
  .block {
    padding: 0 50px;
  }
  .treeBox {
    width: 100%;
    height: 400px;
    box-sizing: border-box;
    border: 1px solid #ccc;
    overflow: scroll;
    &::-webkit-scrollbar {
      display: unset;
      //   color: #000;
      width: 20px;
      height: 0px;
    }
    &::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/
      //   border-radius: 10px;
      background-color: skyblue;
      background-image: -webkit-linear-gradient(
        45deg,
        rgba(255, 255, 255, 0.2) 25%,
        transparent 25%,
        transparent 50%,
        rgba(255, 255, 255, 0.2) 50%,
        rgba(255, 255, 255, 0.2) 75%,
        transparent 75%,
        transparent
      );
    }
    &::-webkit-scrollbar-track {
      /*滚动条里面轨道*/
      box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: #ededed;
      //   border-radius: 10px;
    }
  }
  .search-tree {
    display: flex;
    box-sizing: border-box;
    margin-bottom: 20px;
    /deep/.el-input,
    .el-input--suffix {
      //   width: 70%;
      margin-right: 40px;
    }
  }
}
.parameter-list {
  margin-bottom: 10px;
  .label,
  .value {
    display: inline-block;
    text-align: center;
    border: 1px solid #ccc;
    &::placeholder {
      color: #ccc;
    }
  }
  .del {
    margin-left: 20px;
    width: 16px;
    height: 16px;
    // height: 100%;
    background-color: #666;
    color: #fff;
    border-radius: 8px;
    text-align: center;
    line-height: 100%;
    font-size: 14px;
    display: inline-block;
  }
}
</style>